import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geomancy/styles/index.dart';
import 'package:geomancy/widgets/common_header.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebViewPage extends StatefulWidget {
  final String url;
  const WebViewPage({super.key, required this.url});

  @override
  State<WebViewPage> createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {
  late final WebViewController controller;
  String? pageTitle;
  int percent = 0;

  @override
  void initState() {
    super.initState();
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            setState(() {
              percent = progress;
            });
          },
          onPageFinished: (String url) async {
            final title = await controller.getTitle();
            setState(() {
              pageTitle = title;
            });
          },
        ),
      )
      ..loadRequest(Uri.parse(widget.url));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CommonHeader.appBar(
        context: context,
        backgroundColor: Colors.white,
        title: pageTitle ?? '',
      ),
      backgroundColor: Colors.white,
      body: Stack(
        children: [
          WebViewWidget(controller: controller),
          if (percent < 100)
            Container(
              width: (750.w * (percent/100)),
              height: 6.w,
              color: ColorStyle.red,
            ),
        ],
      ),
    );
  }
}
